package jp.sourceforge.akjrcp.ffmpeg;

import com.akjava.lib.standards.process.ProcessMonitor;
import com.akjava.lib.standards.process.ProcessPrinter;
import com.akjava.lib.standards.process.SimpleProcessPrinter;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class SimpleCommandExecuter {
public static Log log = LogFactory.getLog(SimpleCommandExecuter.class);
protected String[] command;
protected String oneLineCommand;
private Process process;
private ProcessPrinter printer;
private long waitForCloseStream=10000; 
public SimpleCommandExecuter(String[] command){
	this.command=command;
	printer = new SimpleProcessPrinter();
}
public SimpleCommandExecuter(String command){
	this.oneLineCommand=command;
	printer = new SimpleProcessPrinter();
}
public void execute(){
	Runtime runtime=Runtime.getRuntime();
	try {
		if(oneLineCommand!=null){
			process = runtime.exec(oneLineCommand);
		}else{
			process = runtime.exec(command);
		}
	
		
		ProcessMonitor monitor=new ProcessMonitor(process,printer);
		monitor.startMonitor();
		
		try {
			process.waitFor();
			long c=System.currentTimeMillis();
			while(System.currentTimeMillis()<c+waitForCloseStream){
				if(monitor.isErrorClosed() && monitor.isInputClosed()){
					break;
				}else{
					log.warn("wait:input reading");
					Thread.sleep(100);
				}
			}
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}	
}
public ProcessPrinter getPrinter() {
	return printer;
}
public void setPrinter(ProcessPrinter printer) {
	this.printer = printer;
}
public Process getProcess() {
	return process;
}

public void cancel(){
	if(process!=null){
		process.destroy();
	}
}


}
